package com.knight.admin.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.knight.admin.common.constant.Constant;
import com.knight.admin.utils.MD5Util;

public class LoginController extends Controller {

	private static final Logger logger = Logger.getLogger(LoginController.class);

	/**
	 * 进入登录页面
	 */
	public void loginPage() {
		String userName = getPara("type");
		if (StringUtils.isNotBlank(userName)) {
			setAttr("errorMsg", "账号或密码错误");
		}
		render("login/login.html");
	}

	/**
	 * 登录方法
	 */
	public void login() {

		String userName = getPara("userName");

		boolean validateCaptcha = this.validateCaptcha("inputRandomCode");

		if (validateCaptcha) {
			String loginUserName = PropKit.get("loginUserName");
			if (!loginUserName.equals(userName)) {
				redirect("/login/loginPage?type=1");// 登录失败
			} else {
				String password = getPara("password");
				if (StringUtils.isBlank(password)) {
					redirect("/login/loginPage?type=1");// 登录失败
				} else {
					String loginPassword = PropKit.get("loginPassword");
					if (!loginPassword.equals(MD5Util.string2MD5(password))) {
						//密码不想等
						redirect("/login/loginPage?type=1");// 登录失败
					} else {
						// 登录成功设置session的值
						setSessionAttr(Constant.LOGINUSER, loginUserName);
						redirect("/index");
					}
				}
			}
		} else {
			redirect("/login/loginPage");
		}
	}

	/**
	 * 验证码
	 */
	public void validationCode() {
		// 生成验证码
		this.renderCaptcha();
	}

	/**
	 * 退出登录
	 */
	public void signOut() {
		Object loginUser = getSessionAttr(Constant.LOGINUSER);
		if (loginUser != null) {
			setSessionAttr(Constant.LOGINUSER, null);
		}
		redirect("/login/loginPage");
	}
}
